package com.xwj.controller.front;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.xwj.config.FileUploadCosConfig;
import com.xwj.data.StaticData;
import com.xwj.entity.PassWordEntity;
import com.xwj.entity.RaRegisterUser;
import com.xwj.service.Impl.RegisterUserServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/front/myCenter/person/")
public class FrontPersonalInfoController {

    @Autowired
    private RegisterUserServiceImpl registerUserService;
    @Autowired
    private FileUploadCosConfig fileUploadCos;

    @RequestMapping(value = "personalData", method = RequestMethod.GET)
    public ModelAndView personalData(ModelAndView modelAndView) {
        modelAndView.setViewName("/front/personal/personal");
        return modelAndView;
    }

    @RequestMapping(value = "updatePwdView", method = RequestMethod.GET)
    public ModelAndView updatePwdView(ModelAndView modelAndView) {
        modelAndView.setViewName("/front/personal/updatePwd");
        return modelAndView;
    }

    @RequestMapping(value = "updatePersonalData", method = RequestMethod.POST)
    public Map<String, Object> updatePersonalData(RaRegisterUser raRegisterUser, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        ServletContext context = request.getServletContext();
        String userId = (String) context.getAttribute(StaticData.REGISTER_USER_LOGIN_ATTRIBUTE);
        String photo = registerUserService.getUrlformRedis(userId + "_upload_front_registerUser_picture");
        if (StringUtils.isNotBlank(photo))
            raRegisterUser.setPhoto(photo);
        if (registerUserService.updateOtherProperty(raRegisterUser) > 0) {
            registerUserService.deleteFromRedis(userId + "_upload_front_registerUser_picture");
            context.setAttribute(StaticData.REGISTER_USER_DATA, registerUserService.findUserById(raRegisterUser.getId()));
            map.put("msg", "修改成功");
        } else
            map.put("msg", "修改失败");
        return map;
    }

    @RequestMapping(value = "updatePwd", method = RequestMethod.POST)
    public Map<String, Object> updatePwd(PassWordEntity passWordEntity, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        ServletContext context = request.getServletContext();
        String userId = (String) context.getAttribute(StaticData.REGISTER_USER_LOGIN_ATTRIBUTE);
        PassWordEntity entity = registerUserService.getUserPassWord(userId);
        passWordEntity.setId(userId);
        String tmp = new Md5Hash(passWordEntity.getPassword(), entity.getSalt()).toString();
        if (StringUtils.isBlank(passWordEntity.getPassword()))
            map.put("msg", "没做任何修改");
        else {
            if (entity.getPassword().equals(new Md5Hash(passWordEntity.getOldPassword(), entity.getSalt()).toString())) {
                if (tmp.equals(entity.getPassword()))
                    map.put("msg", "不可与旧密码相同");
                else {
                    if (registerUserService.updatePassword(passWordEntity) > 0) {
                        context.removeAttribute(StaticData.REGISTER_USER_LOGIN_ATTRIBUTE);
                        context.removeAttribute(StaticData.REGISTER_USER_DATA);
                        map.put("msg", "密码修改成功,请重新登录");
                    } else
                        map.put("msg", "密码修改失败");
                }
            } else
                map.put("msg", "旧密码验证不匹配");
        }
        return map;
    }

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public String handleFileUpload(HttpServletRequest request) {
        ServletContext context = request.getServletContext();
        String accountid = (String) context.getAttribute(StaticData.REGISTER_USER_LOGIN_ATTRIBUTE);
        String localPathDir = "/registerUserphoto";
        String localRealPathDir = request.getSession().getServletContext().getRealPath(localPathDir);
        File localSaveFile = new File(localRealPathDir);
        if (!localSaveFile.exists()) localSaveFile.mkdirs();
        String result = null;
        try {
            MultipartFile multipartFile = ((MultipartHttpServletRequest) request).getFile("file");
            String fileName = localRealPathDir + File.separator + multipartFile.getOriginalFilename();
            File file = new File(fileName);
            multipartFile.transferTo(file);
            result = fileUploadCos.uploadFile("/registerUserphoto/", fileName, multipartFile.getOriginalFilename());
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.getInteger("code") == 0) {
                JsonObject jsonObject1 = new JsonObject();
                jsonObject1.addProperty("access_url", jsonObject.getJSONObject("data").getString("access_url"));
                registerUserService.addUrlToRedis(jsonObject1.toString(), accountid + "_upload_front_registerUser_picture");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
